package cn.sccdlg.springmvc.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/24 22:14
 * 用户登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 登录验证，有登录信息放行，反之重定向登录界面
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是登录页面则放行
        if (request.getRequestURI().indexOf("login.action") >= 0) {
            System.out.println("访问登录界面，放行");
            return true;
        }
        HttpSession session = request.getSession();
        //如果用户已登录也放行
        if (session.getAttribute("activeUser") != null) {
            System.out.println("有登录信息，放行");
            return true;
        }
        //用户没有登录挑战到登录页面
        request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);
        return false;
    }

}
